package com.dindang.propertyfee.mvp.ui.widget;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dindang.propertyfee.R;
import com.dindang.propertyfee.mvp.model.entity.Build;
import com.dindang.propertyfee.mvp.model.entity.CityEntity;
import com.jess.arms.utils.ArmsUtils;
import com.longxi.gamer_base.utils.SharedPreferencesUtils;
import com.longxi.gamer_base.widget.EmptyLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by cxw on & 2018/11/8
 */
public class CommunitySelectDialog extends Dialog {

    public CommunitySelectDialog(@NonNull Context context) {
        super(context);
    }

    public CommunitySelectDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected CommunitySelectDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public static class Builder  implements AbsListView.OnScrollListener {
        private Context context;
        private OnCommunityListener listener;
        private String title;

        protected List<Build.Building> hotCityList = new ArrayList<>();
        protected List<Build.Building> totalCityList = new ArrayList<>();
        protected List<Build.Building> curCityList = new ArrayList<>();
        protected CityListAdapter cityListAdapter;
        private String locationCity, locationCode, curSelCity;
        private boolean isScroll = false;
        private boolean mReady = false;
        private TextView overlay; // 对话框首字母TextView
        private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置

        private Handler handler;
        private OverlayThread overlayThread; // 显示首字母对话框

        public Builder(Context context) {
            this.context = context;
        }

        public Builder setTitle(String title){
            if("".equals(title)){
                this.title = "请设置标题";
            }else{
                this.title = title;
            }
            return this;
        }

        public Builder setProperty(OnCommunityListener listener) {
            this.listener = listener;
            return this;
        }

        private ImageView iv_dialog_close;
        private TextView tv_title;
        private ListView total_city_lv;
        private LetterListView total_city_letters_lv;
        private EmptyLayout emptylayout;
        private TextView no_search_result_tv;
        private TextView tv_cancle;
        private TextView tv_sure;
        private RelativeLayout rl;
        private Build.Building isSelectCityEntity = new Build.Building();

        private CommunitySelectDialog dialog;

        public CommunitySelectDialog create() {
            dialog = new CommunitySelectDialog(context);
            View view = LayoutInflater.from(context).inflate(R.layout.propertyfee_dialog_community_select, null);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//加上这一句，取消原来的标题栏，没加这句之前，发现在三星的手机上会有一条蓝色的线
            dialog.setContentView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            iv_dialog_close = view.findViewById(R.id.propertyfee_iv_dialog_close);
            tv_title = view.findViewById(R.id.propertyfee_tv_title);
            total_city_lv = view.findViewById(R.id.propertyfee_total_city_lv);
            total_city_letters_lv = view.findViewById(R.id.propertyfee_total_city_letters_lv);
            emptylayout = view.findViewById(R.id.propertyfee_emptylayout);
            no_search_result_tv = view.findViewById(R.id.propertyfee_no_search_result_tv);
            tv_cancle = view.findViewById(R.id.propertyfee_tv_cancle);
            tv_sure = view.findViewById(R.id.propertyfee_tv_sure);

            rl = view.findViewById(R.id.propertyfee_rl);
            ViewGroup.LayoutParams params = rl.getLayoutParams();
            int reserved = 150;//顶部预留
            int otherSites = 107;//其它占位的控件
            int nestedScrollViewHeight = ArmsUtils.getScreenHeidth(context) - ArmsUtils.dip2px(context, (otherSites + reserved));
            params.height = nestedScrollViewHeight;
            rl.setLayoutParams(params);

            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            tv_title.setText(title);
            iv_dialog_close.setOnClickListener(v -> dialog.dismiss());
            tv_cancle.setOnClickListener(v -> dialog.dismiss());
            tv_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateHot();
                    cityListAdapter.notifyDataSetChanged();
                    listener.onSure(isSelectCityEntity);
                }
            });
//            handler = new Handler();
//            overlayThread = new OverlayThread();
            return dialog;
        }

        public void updateData(List<Build.Building> _hotCityList, List<Build.Building> _totalCityList, List<Build.Building> _curCityList){
            hotCityList.clear();
            totalCityList.clear();
            curCityList.clear();

            hotCityList = _hotCityList;
            totalCityList = _totalCityList;
            curCityList = _curCityList;

            cityListAdapter = new CityListAdapter(context, totalCityList, hotCityList);
            total_city_lv.setAdapter(cityListAdapter);
            total_city_lv.setOnScrollListener(this);
            total_city_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Build.Building cityEntity = totalCityList.get(position);
                    if(totalCityList.contains(isSelectCityEntity)){
                        totalCityList.get(totalCityList.indexOf(isSelectCityEntity)).setSelect(false);
                    }
                    cityEntity.setSelect(true);
                    isSelectCityEntity = cityEntity;
                    updateHot();
                    cityListAdapter.notifyDataSetChanged();
                    listener.onClick(cityEntity);
                }
            });
            total_city_letters_lv.setOnTouchingLetterChangedListener(new LetterListViewListener());
            initOverlay();
            emptylayout.hide();
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == SCROLL_STATE_TOUCH_SCROLL
                    || scrollState == SCROLL_STATE_FLING) {
                isScroll = true;
            } else {
                isScroll = false;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            if (!isScroll) {
                return;
            }

            String key = getAlpha(totalCityList.get(firstVisibleItem).key);
            if (mReady && !"0".equals(key)) {
//                overlay.setText(key);
//                overlay.setVisibility(View.VISIBLE);
//                handler.removeCallbacks(overlayThread);
//                // 延迟让overlay为不可见
//                handler.postDelayed(overlayThread, 700);
            }
        }

        /**
         * 初始化汉语拼音首字母弹出提示框
         */
        private void initOverlay() {
            mReady = true;
            LayoutInflater inflater = LayoutInflater.from(context);
            overlay = (TextView) inflater.inflate(R.layout.propertyfee_overlay, null);
            overlay.setVisibility(View.INVISIBLE);
//            WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
//                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
//                    WindowManager.LayoutParams.TYPE_APPLICATION,
//                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
//                    PixelFormat.TRANSLUCENT);
//            WindowManager windowManager = (WindowManager) context
//                    .getSystemService(Context.WINDOW_SERVICE);
//            windowManager.addView(overlay, lp);
        }

        public void setInitial(String[] keys) {
            total_city_letters_lv.b = keys;
            total_city_letters_lv.invalidate();
        }

        private class LetterListViewListener implements
                LetterListView.OnTouchingLetterChangedListener {

            @Override
            public void onTouchingLetterChanged(final String s) {
                isScroll = false;
                if (alphaIndexer.get(s) != null) {
                    int position = alphaIndexer.get(s);
                    total_city_lv.setSelection(position);
//                    overlay.setText(s);
//                    overlay.setVisibility(View.VISIBLE);
//                    handler.removeCallbacks(overlayThread);
//                    // 延迟让overlay为不可见
//                    handler.postDelayed(overlayThread, 700);
                }
            }
        }

        /**
         * 设置overlay不可见
         */
        private class OverlayThread implements Runnable {
            @Override
            public void run() {
                overlay.setVisibility(View.GONE);
            }
        }

        /**
         * 总城市适配器
         */
        public class CityListAdapter extends BaseAdapter {
            private Context context;

            private List<Build.Building> totalCityList;
            private List<Build.Building> hotCityList;
            private LayoutInflater inflater;
            final int VIEW_TYPE = 3;

            CityListAdapter(Context context,
                            List<Build.Building> totalCityList,
                            List<Build.Building> hotCityList) {
                this.context = context;
                this.totalCityList = totalCityList;
                this.hotCityList = hotCityList;
                inflater = LayoutInflater.from(context);

                alphaIndexer = new HashMap<>();

                for (int i = 0; i < totalCityList.size(); i++) {
                    // 当前汉语拼音首字母
                    String currentStr = totalCityList.get(i).key;

                    String previewStr = (i - 1) >= 0 ? totalCityList.get(i - 1).key : " ";
                    if (!previewStr.equals(currentStr)) {
                        String name = getAlpha(currentStr);
                        alphaIndexer.put(name, i);
                    }
                }
            }

            @Override
            public int getViewTypeCount() {
                return VIEW_TYPE;
            }

            @Override
            public int getItemViewType(int position) {
                return position < 2 ? position : 2;
            }

            @Override
            public int getCount() {
                return totalCityList == null ? 0 : totalCityList.size();
            }

            @Override
            public Object getItem(int position) {
                return totalCityList.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                final TextView curCityNameTv;
                ViewHolder holder;
                int viewType = getItemViewType(position);
                if (viewType == 0) { //历史记录
                    convertView = inflater.inflate(R.layout.propertyfee_item_recent_city, null);
                    GridView hotCityGv = convertView.findViewById(R.id.propertyfee_recent_city_gv);
                    TextView tv_history = convertView.findViewById(R.id.propertyfee_tv_history);
                    hotCityGv.setAdapter(new HotCityListAdapter(context, this.hotCityList));
                    hotCityGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
                            Build.Building cityEntity = hotCityList.get(position);
                            if(totalCityList.contains(isSelectCityEntity)){
                                totalCityList.get(totalCityList.indexOf(isSelectCityEntity)).setSelect(false);
                            }
                            isSelectCityEntity = cityEntity;
                            updateHot();
                            cityListAdapter.notifyDataSetChanged();
                            listener.onClick(cityEntity);
                        }
                    });
                    if(hotCityList.size() == 0){
                        hotCityGv.setVisibility(View.GONE);
                        tv_history.setVisibility(View.GONE);
                    }else{
                        hotCityGv.setVisibility(View.VISIBLE);
                        tv_history.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (null == convertView) {
                        convertView = inflater.inflate(R.layout.propertyfee_item_city_list, null);
                        holder = new ViewHolder(convertView);
                        convertView.setTag(holder);
                    } else {
                        holder = (ViewHolder) convertView.getTag();
                    }

                    Build.Building cityEntity = totalCityList.get(position);
//                    holder.cityKeyTv.setVisibility(View.VISIBLE);
//                    holder.cityKeyTv.setText(getAlpha(cityEntity.key));
                    holder.cityNameTv.setText(cityEntity.name);

//                    if (position >= 1) {
//                        Build.Building preCity = totalCityList.get(position - 1);
//                        if (preCity.key.equals(cityEntity.key)) {
//                            holder.cityKeyTv.setVisibility(View.GONE);
//                        } else {
//                            holder.cityKeyTv.setVisibility(View.VISIBLE);
//                        }
//                    }

                    if(cityEntity.isSelect){
                        holder.ivSelect.setImageResource(R.mipmap.propertyfee_ic_select_press);
                    }else{
                        holder.ivSelect.setImageResource(R.mipmap.propertyfee_ic_select_normal);
                    }

                    holder.ivSelect.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Build.Building cityEntity = totalCityList.get(position);
                            if(totalCityList.contains(isSelectCityEntity)){
                                totalCityList.get(totalCityList.indexOf(isSelectCityEntity)).setSelect(false);
                            }
                            cityEntity.setSelect(true);
                            isSelectCityEntity = cityEntity;
                            cityListAdapter.notifyDataSetChanged();
                        }
                    });

                }

                return convertView;
            }

            public class ViewHolder {
                TextView cityNameTv;
                TextView cityKeyTv;
                ImageView ivSelect;
                public ViewHolder(View convertView){
                    cityNameTv = convertView.findViewById(R.id.propertyfee_city_name_tv);
                    cityKeyTv = convertView.findViewById(R.id.propertyfee_city_key_tv);
                    ivSelect = convertView.findViewById(R.id.propertyfee_iv_select);
                }
            }
        }

        /**
         * 热门城市适配器
         */
        public class HotCityListAdapter extends BaseAdapter {

            private List<Build.Building> cityEntities;
            private LayoutInflater inflater;

            HotCityListAdapter(Context mContext, List<Build.Building> cityEntities) {
                this.cityEntities = cityEntities;
                inflater = LayoutInflater.from(mContext);
            }

            @Override
            public int getCount() {
                return cityEntities == null ? 0 : cityEntities.size();
            }

            @Override
            public Object getItem(int position) {
                return cityEntities.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                if (null == convertView) {
                    convertView = inflater.inflate(R.layout.propertyfee_item_city_list_grid, null);
                    holder = new ViewHolder(convertView);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                Build.Building cityEntity = cityEntities.get(position);
                holder.cityNameTv.setText(cityEntity.name);

                return convertView;
            }

            public class ViewHolder {

                TextView cityNameTv;
                public ViewHolder(View view) {
                    cityNameTv = view.findViewById(R.id.propertyfee_city_list_grid_item_name_tv);
                }
            }
        }

        /**
         * 获得首字母
         */
        private String getAlpha(String key) {
            return key;
        }

        /**
         * 更新历史纪录
         */
        private void updateHot() {
            if(hotCityList.size() >= 4){
                hotCityList.remove(hotCityList.size() - 1);
                hotCityList.add(0, isSelectCityEntity);
            }else{
                hotCityList.add(0, isSelectCityEntity);
            }
            String json = JSON.toJSONString(hotCityList);
            SharedPreferencesUtils.setParam(context.getApplicationContext(), "XIAOQUHISTORY", json);

        }

        public void dismiss(){
            if(dialog != null){
                dialog.dismiss();
            }
        }

        public void show(){
            if(dialog != null){
                dialog.show();
            }
        }
    }

    @Override
    public void show() {
        super.show();
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.gravity = Gravity.BOTTOM;
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(layoutParams);
    }

    public interface OnCommunityListener {
        void onClick(Build.Building cityEntity);
        void onSure(Build.Building cityEntity);
    }

}
